<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\GroupBooking;
use App\Models\GroupBookingUser;
use App\Models\groupCatch;
use App\Models\Renting;
use App\Models\StoreGoods;
use App\Service\CommonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class PackGoodsController extends Controller
{
    public static function wxGroupBookingSuccess($post)
    {
        dd($post);
    }

    /**
     * @param Request $request
     * @return array|false
     * @throws \Throwable
     * User: 张浩
     * Date: 2022/11/20
     * Time: 21:10
     * 加入别人发起的拼团
     */
    public function wxGroupBookingAddition(Request $request)
    {
        //获取前端传来的数据
        $post['groupbooking_id'] = $request->get('id', '');
        $post['u_id'] = $request->get('uid', '');
        //根据当前接到的数据查询数据
        $list = GroupBookingUser::GroupbookingUser($post['groupbooking_id'], $post['u_id']);
        //判断数据是否为空
        if (!empty($list)) {
            //判断当前团是否自己创建
            if ($list['colonel'] == 1) return commonService::fail(9999, '您不能参加自己的团', []);
            //判断数据状态是否已经参团
            if ($list['u_stare'] == 1) return commonService::fail(9999, '您已参加此团', []);
        }
        //根据数据获取拼团信息
        $groupbooking = GroupBooking::GroupbookingFirst($post['groupbooking_id']);
        //判断是否获取到当前团的数据
        if (empty($groupbooking)) return commonService::fail(9999, '没有找到当前团的信息', []);
        //获取当前有多少人参团
        $num = count(GroupBookingUser::where('groupbooking_id', $groupbooking['id'])->where('u_stare', 1)->get());
        //判断当前团有没有超出成团人数
        if ($num >= $groupbooking['groupbooking_type']) return commonService::fail(9999, '当前团人数已够请选择别的团', []);
        $num = $num + 1;
        //判断当前团加自己能不能成团
        if ($num >= $groupbooking['groupbooking_type']) {
            //当自己加入后拼团成功时调用
            $user = self::wxGroupBookingSuccess($post);
            return $user;
        }
        //判断当前是否拼团成功
        try {
            \DB::beginTransaction();
            //添加自己的信息
            $user = GroupBookingUser::GroupbookingUserCreate($post);
            ///修改商品库存
            $StoreGoodsFirst = StoreGoods::GoodsFirst($groupbooking['groupbooking_combo_id']);
            if ($StoreGoodsFirst['stock'] > 0 && !empty($StoreGoodsFirst)) {
                $StoreGoodsFirst['stock'] = $StoreGoodsFirst['stock'] - 1;
            } else {
                return false;
            }
            $StoreGoodsRepertory = StoreGoods::StoreGoodsRepertory($groupbooking['groupbooking_combo_id'], $StoreGoodsFirst);
            if ($user && $StoreGoodsRepertory) {
                \DB::commit();
                return commonService::success(200, '加入拼团成功', $user['groupbooking_id']);
            }
        } catch (\Exception $exception) {
            \DB::rollBack();
            return commonService::fail(9999, '加入拼团失败，请重试', []);
        }
    }

    /**
     * @param Request $request
     * @return array
     * @throws \Throwable
     * User: 张浩
     * Date: 2022/11/20
     * Time: 18:52
     * 发起拼团
     */
    public function wxGroupBookingAdd(Request $request)
    {
        //获取前端传来的参数
        $post['groupbooking_combo_id'] = $request->get('id', '');
        $post['groupbooking_type'] = $request->get('groupbooking_type', 2);
        $post['groupbooking_uid'] = $request->get('uid', '');
        //判断用户信息
        if (empty($post['groupbooking_uid'])) {
            return commonService::fail(9999, '用户信息有误请登录', []);
        }
        //根据用户id获取用户信息
        $user = Renting::rentingFirst($post['groupbooking_uid']);
        //判断用户信息是否获取成功
        if (empty($user)) return ['code' => 9999, 'msg' => '用户信息获取失败', 'data' => []];
        //根据用户id和商品id查找数据
        $Group = GroupBooking::GroupbookingDetection($post['groupbooking_uid'], $post['groupbooking_combo_id']);
        //判断该用户当前是否正在拼这件商品
        if (!empty($Group)) {
            //获取当前拼团是否过期
            $time = (strtotime(date($Group['created_at'])) + (60 * 60 * 24 * $Group['groupbooking_time'])) - time();
            //判断拼团是否过期
            if ($time > 0) return commonService::fail(9999, '此商品您正在拼团快去查看吧', []);
        }
        //添加团名称
        $post['groupbooking_name'] = $user['nickName'] . '的团';
        //事务添加拼团信息
        try {
            \DB::beginTransaction();
            //添加拼团 信息
            $GroupBookingCreate = GroupBooking::GroupbookingCreate($post);
            //组装团长信息
            $posts = [
                'groupbooking_id' => $GroupBookingCreate->id,
                'u_id' => $post['groupbooking_uid'],
                'colonel' => 1
            ];
            //添加团长
            $GroupBookingUserCreate = GroupBookingUser::GroupbookingUserCreate($posts);
            //修改商品库存
            $StoreGoodsFirst = StoreGoods::GoodsFirst($post['groupbooking_combo_id']);
            if ($StoreGoodsFirst['stock'] > 0 && !empty($StoreGoodsFirst)) {
                $StoreGoodsFirst['stock'] = $StoreGoodsFirst['stock'] - 1;
            }
            $StoreGoodsRepertory = StoreGoods::StoreGoodsRepertory($post['groupbooking_combo_id'], $StoreGoodsFirst);
            if ($GroupBookingCreate && $GroupBookingUserCreate && $StoreGoodsRepertory) {
                \DB::commit();
                return commonService::success(200, '开启拼团成功', $GroupBookingCreate->id);
            }
        } catch (\Exception $exception) {
            \DB::rollBack();
            return commonService::fail(9999, '拼团开启失败请重试', []);
        }
    }

    /**
     * @param Request $request
     * @return array
     * User: 张浩
     * Date: 2022/11/20
     * Time: 18:37
     * 拼团商品详情页数据获取
     */
    public function wxGoodsDetails(Request $request)
    {
        $id = $request->get('id', '');
        $uid = $request->get('uid', '');
        //获取商品信息
        $goodsdetails = StoreGoods::GoodsFirst($id);
        if (empty($goodsdetails)) return commonService::fail(9999, '商品不存在', []);
        //商品评论功能未完成，
        $goodsdetails['comment'] = '';
        //获取当前商品下所有拼团信息
        $GroupBookingmessage = GroupBooking::GroupBookingmessage($id);
        foreach ($GroupBookingmessage as $key => $value) {
            $GroupBookingmessage[$key]['referrer'] = GroupBookingUser::wxGroupBookinguidlist($value['id']);
        }
        //根据用户id获取用户地址
        $address = Address::addressUidGet($uid);
        if (empty($address)) {
            $address = '';
        }
        //根据商品信息获取商品评论信息
        $commentlist = GoodsComment::goodcommentfirst($id);
        if (empty($commentlist)){
            $commentlist='';
        }
        $comment = CommonService::getTree($commentlist);
        dd($comment);
        //封装数据
        $post = [
            'goodsdetails' => $goodsdetails,
            'address' => $address,
            'GroupBookingmessage' => $GroupBookingmessage,
            'comment' => $comment
        ];
        return commonService::success(200, '数据获取成功', $post);
    }

    /**
     * @param Request $request
     * @return array
     * User: 张浩
     * Date: 2022/11/17
     * Time: 18:58
     * 拼团记录数据获取
     */
    public function wxGroupBookingDetails(Request $request)
    {
        $id = $request->get('id', 0);
        $uid = $request->get('uid', 0);
        //获取当前拼团相关数据
        $userlist = $this->wxGroupBookinguidlist($uid);
        //获取拼团成员信息
        $userlist['GroupbookingUser'] = GroupBookingUser::wxGroupBookingDetails($id);
        return commonService::success(200, '数据获取成功', $userlist);
    }

    /**
     * @param $uid
     * User: 张浩
     * Date: 2022/11/16
     * Time: 20:27
     * 用户有拼团数据时获取相关数据
     */
    public function wxGroupBookinguidlist($uid)
    {
        //判断当前用户有没有主动发起的团
        $userlist = GroupBooking::GroupbookingUidFirst($uid);
        if (empty($userlist)) {
            $userlist = '';
        } else {
            //获取当前团成员
            $wxGroupBookinguidlist = GroupBookingUser::wxGroupBookinguidlist($userlist['id']);
            //判断当前团有没有成员
            if ($wxGroupBookinguidlist == 0) {
                $userlist['percentage'] = 100;
                $userlist['shortof'] = $userlist['groupbooking_type'];
            } else {
                //计算百分比和差多少人
                $userlist['percentage'] = ($wxGroupBookinguidlist / $userlist['groupbooking_type']) * 100;
                $userlist['shortof'] = $userlist['groupbooking_type'] - $wxGroupBookinguidlist;
            }
            //获取当前拼团还有多久过期
            $userlist['GroupBookingTime'] = (strtotime(date($userlist['created_at'])) + (60 * 60 * 24 * $userlist['groupbooking_time'])) - time();
        }
        return $userlist;
    }

    /**
     * @param Request $request
     * @return array
     * User: 张浩
     * Date: 2022/11/16
     * Time: 20:27
     * 拼团列表页数据获取
     */
    public function wxGroupBookingList(Request $request)
    {
        $uid = $request->get('uid', '');
        //判断当前用户是否登录
        if (!empty($uid)) {
            $userlist = $this->wxGroupBookinguidlist($uid);
        } else {
            $userlist = '';
        }
        //获取拼团商品数据
        $lists = Redis::hgetall('GroupbookingShow');
        //判断缓存中是否有数据
        if (!empty($lists)) {
            $lists = json_decode($lists, true);
        } else {
            //没有数据时从mysql数据库中获取
            $result = StoreGoods::wxGroupBookingList();
            $lists = $result['data'];
        }
        if (empty($lists)) {
            $list = [];
        } else {
            $list = [];
            foreach ($lists as $value) {
                //避免字符串截断乱码情况
                $value['store_name'] = mb_convert_encoding(substr($value['store_name'], 0, 36) . '...', 'UTF-8', 'UTF-8');
                $list[] = $value;
            }
        }
        //拼装返回数据
        $post = [
            'list' => $list,
            'userlist' => $userlist
        ];
        return CommonService::success(200, '拼团数据获取成功', $post);
    }


}
